package com.talent.web.config.security;

import com.talent.web.model.entity.SysUser;
import com.talent.web.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
/**
 *
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: userDetailService的实现类
 */
@Service("talentUserDetailService")
public class TalentUserDetailService implements UserDetailsService, UserDetailsPasswordService {

    @Autowired
    private ISysUserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.selectUserByUsername(username);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException(username);
        }

        List<String> permission = userService.getPermission(user.getId());
        TalentUserDetails userDetails = new TalentUserDetails();
        userDetails.setUsername(username);
        userDetails.setPassword(user.getPassword());
        userDetails.setId(user.getId());
        userDetails.setAuthorities(permission);
        return userDetails;
    }
    public TalentUserDetails loadUserByMobile(String phone) {
        SysUser user = userService.selectUserByMobile(phone);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException(phone);
        }

        List<String> permission = userService.getPermission(user.getId());
        TalentUserDetails userDetails = new TalentUserDetails();
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPassword());
        userDetails.setId(user.getId());
        userDetails.setAuthorities(permission);
        return userDetails;
    }

    /**登录过后 会自动升级密码*/
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
         userService.upgradePassword(user.getUsername(),newPassword);
         return user;
    }
}
